package com.yugao.fintech.draper.scheduled.controller;

import cn.hutool.core.lang.Assert;
import com.yugao.fintech.draper.core.model.ResultVO;
import com.yugao.fintech.draper.datasource.entity.PageResult;
import com.yugao.fintech.draper.quartz.utils.CronUtils;
import com.yugao.fintech.draper.scheduled.dto.QuartzJobDTO;
import com.yugao.fintech.draper.scheduled.dto.QuartzJobQuery;
import com.yugao.fintech.draper.scheduled.service.QuartzJobService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * 定时任务调度
 */
@RestController
@RequestMapping("/job")
@RequiredArgsConstructor
public class QuartzJobController {

    private final QuartzJobService quartzJobService;

    @GetMapping(value = "/page")
    public ResultVO<PageResult<QuartzJobDTO>> page(QuartzJobQuery page) {
        return ResultVO.success(PageResult.success(quartzJobService.page(page)));
    }

    @PostMapping(value = "/add")
    public ResultVO<QuartzJobDTO> add(@RequestBody QuartzJobDTO quartzJobDto) {
        validJob(quartzJobDto);
        return ResultVO.success(quartzJobService.add(quartzJobDto));
    }

    @PostMapping(value = "/update")
    public ResultVO<QuartzJobDTO> update(@RequestBody QuartzJobDTO quartzJobDto) {
        validJob(quartzJobDto);
        return ResultVO.success(quartzJobService.update(quartzJobDto));
    }

    @DeleteMapping(value = "/delete")
    public ResultVO<Boolean> delete(Long id) {
        return ResultVO.success(quartzJobService.deleteByJobId(id));
    }

    @GetMapping(value = "/findById")
    public ResultVO<QuartzJobDTO> findById(Long id) {
        return ResultVO.success(quartzJobService.findById(id));
    }

    /**
     * 定时任务状态修改
     */
    @PutMapping("/changeStatus")
    public ResultVO<Boolean> changeStatus(@RequestBody QuartzJobDTO quartzJobDto) {
        return ResultVO.success(quartzJobService.changeStatus(quartzJobDto));
    }

    /**
     * 定时任务立即执行一次
     */
    @PutMapping("/run")
    public ResultVO<Void> run(@RequestBody QuartzJobDTO quartzJobDto) {
        quartzJobService.run(quartzJobDto);
        return ResultVO.success();
    }

    private void validJob(QuartzJobDTO quartzJobDto) {
        Assert.isTrue(CronUtils.isValid(quartzJobDto.getCronExpression()), "新增任务'" + quartzJobDto.getJobName() + "'失败，Cron表达式不正确");
    }
}